package com.niuke;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * 63. 树状结构查询
 * https://zhuanlan.zhihu.com/p/645572837
 */
public class NiukeMoni63 {

    public static Map<String, List<String>> map;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int row = Integer.parseInt(scanner.nextLine());

        map = new HashMap<>();
        for (int i = 0; i < row; i++) {
            String[] input = scanner.nextLine().split(" ");
            String key = input[1];
            String value = input[0];

            List<String> item = map.getOrDefault(key, new ArrayList<>());
            item.add(value);
            map.put(key, item);
        }

        List<String> keys = new ArrayList<>();
        keys.add(scanner.nextLine());
        List<String> result = new ArrayList<>();
        dfs(keys, result);

        System.out.println(Arrays.toString(result.toArray()));
    }

    public static void dfs(List<String> keys, List<String> ans) {
        for (int i = 0; i < keys.size(); i++) {
            List<String> nextKeys = map.get(keys.get(i));
            if (nextKeys != null && keys.size() > 0) {
                ans.addAll(nextKeys);
                dfs(nextKeys, ans);
            }
        }
    }

    private static NiukeMoni63 a;

    // 单例模式不能是内部类
    public static NiukeMoni63 getInstance() {
        if (a == null) {
            synchronized (NiukeMoni63.class) {
                if (a == null) {
                    a = new NiukeMoni63();
                }
            }
        }
        return a;
    }

    private NiukeMoni63() {

    }

}
